// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var dialog = require("dialog");
	var validate = require("validate");
	var constant = require("constant");
	var router = require("../hash/pageRouter");
	var css_organization = require("./organization.css");
	var css_autocomplete = require("../../../component/autocomplete/jquery.autocomplete.css");
	var css_tree = require("../../../js/zTree/css/zTreeStyle/zTreeStyle.css");
	var html_member_permission = require("./memberMission_create.html");
	var html_member_position = require("./memberMission_move.html");
	var databind = require("databind");
	var subOrg = 0; //是否包含子部门,默认不包含
	var orgId; //组织ID
	var employeeId; //员工ID
	var imgSrc; //图片路径
	//图片路径变量2，用于测试
	var imgSrcTest;
	var editImgSrc; //原图片路径
	var companyName; //公司名称
	var pageIndex = 1,
		pageSize = 10,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var firstFoucsOnEditManageMnet = 0; //编辑部门是否进行改动
	var oData = {
		subOrg: "",
		orgId: "",
		keyword: "",
		pageSize: pageSize,
		pageIndex: pageIndex,
	};
	var addDepart;
	var addEmployee;
	var confirmDialog;
	var editDepart;
	var editEmployee;
	var init = function() {
		// addDepart = require("./organization-addDepart.html");
		// addEmployee = require("./organization-addEmployee.html");
		// confirmDialog = require("./organization-confirmDialog.html");
		// editDepart = require("./organization-editDepart.html");
		// editEmployee = require("./organization-editEmployee.html");
		// $("#popdialog").html(addDepart);
		initEvent();
		initTree();
		router.init();
		$(".nav_hover", window.parent.document).removeClass("head_link_1");
		$("#company", window.parent.document).addClass("head_link_1");
	};
	// 树形图
	var initTree = function() {
		var setting = {
			view: {
				showLine: true, //是否显示节点间的连线
			},
			data: {
				simpleData: {
					enable: true,
					idKey: "organizationId",
					pIdKey: "parentId",
					organizationId: "organizationId",
					parentId: "parentId",
				}
			},
			callback: {
				onClick: zTreeOnClick,
			}
		};
		base.fnAjax({
			action: "inquireOrganizationList.json",
			type: "POST",
			async: false,
			oData: {},
			fnSuccess: function(data) {
				$.fn.zTree.init($("#tree"), setting, data.datas);
			}
		});
	};
	var zTreeOnClick = function(event, treeId, treeNode) {
		orgId = treeNode.organizationId;
		inquireOrganizationDetail(treeNode.organizationId);
		inquireEmployeeList(treeNode.organizationId);
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			location.href = "../login/login.html";
		}
		
		$(".orgNav").unbind("click").click(function(){
			$(this).parents(".row").find(".col").removeClass("active");
			$(this).parent().addClass("active");
		});
		
		$("#addDepartment").click(function() {
			if (orgId == "" || orgId == undefined) {
				if(orgId!=0){
				base.alert(2, "请先选择部门");
				return;
				}
			}
			dialog.showDialog($("div#addDepartmentDialog"), function() {
				createOrganization();
			});
		});
		$("#editDepartment").click(function() {
			if (orgId == "" || orgId == undefined) {
				if(orgId!=0){
				base.alert(2, "请先选择部门");
				return;
				}
			}
			if (orgId == 0) {
				util.alert("公司信息不能进行更改！");
			} else {
				showEditDepartmentDialog();
				dialog.showDialog($("#editDepartmentDialog"), function() {
					updateOrganization();
				});
			}
		});
		$("#addEmployee").click(function() {
			if (orgId == "" || orgId == undefined) {
				if(orgId!=0){
				base.alert(2, "请先选择部门");
				return;
				}
			}
			$("#uploadImgDiv").css("backgroundImage", "url('../../../res/images/icon/addfile.png')");
			$("#addEmployeeDialog #gender1").prop("checked", "checked");
			employeeEven();
			dialog.showDialog($("#addEmployeeDialog"), function() {
				createEmployee();
			});
		});
		$("#deleteDepartment").click(function() {
			if (orgId == "" || orgId == undefined) {
				base.alert(2, "请先选择部门");
				return;
			}
			dialog.showConfirmDialog("删除部门", "确定要删除该部门么？", function() {
				deleteOrganization();
			});
		});
		$(".oraganization_table").on('click', '.delete_btn', function() {
			var employeeId = $(this).attr("employeeId");
			var employeeName = $(this).attr("employeeName");
			dialog.showConfirmDialog("删除员工", "确定要删除该员工么?", function() {
				deleteEmployee(employeeId);
			});
		});
		//权限分配
		$(".oraganization_table").on('click', '.permision_btn', function() {
			var employeeId = $(this).attr("employeeId");
			$("#popdialog").html(html_member_permission);
			dialog.showDialog($("#create_member_permission"));
			var obj = inquireEmployeeRoleList(employeeId);
			$("#roleIds").html("");
			inquireRoleList();
			$.each(obj, function() {
				var ri = this.roleId;
				$("#roleIds").append("<input type='hidden' name='roleId' value='" + ri + "' />");
				$.each($(".multiSelectOptions input"), function() {
					var $this = $(this);
					if(ri == $this.val()){
						$this.attr("checked", "checked");
					}
				});
			});
			databind.fillForm($("#create_member_permission"), {
				"employeeId": employeeId
			});
			$("#surePermissionBtn").unbind("click").click(function() {
				databind.submitDom($("#create_member_permission"), function() {
					dialog.hideDialog($("#create_member_permission"));
					base.alert(1, "权限分配成功");
				});
			});
			$("#cancelPermissionBtn").unbind("click").click(function() {
				dialog.hideDialog($("#create_member_permission"));
			});
		});
		//更改部门
		$(".oraganization_table").on('click', '.move_btn', function() {
			var employeeId = $(this).attr("employeeId");
			$("#popdialog").html(html_member_position);
			dialog.showDialog($("#move_member_position"));
			inquireOrganizationList();
			databind.fillForm($("#move_member_position"), {
				"empId": employeeId
			});
			
			$("#move_member_position").on("change", "#positionListBody", function(){
				$("#move_member_position input[name=position]").val($(this).find("option:checked").text());
			});
			
			$("#move_member_position .sure_yes").unbind("click").click(function() {
				databind.submitDom($("#move_member_position"), function() {
					dialog.hideDialog($("#move_member_position"));
					base.alert(1, "移动成功！");
					location.reload();
				});
			});
			$("#move_member_position .sure_no").unbind("click").click(function() {
				dialog.hideDialog($("#move_member_position"));
			});
		});
		$("#search img").click(function() {
			oData.pageIndex = 1;
			inquireEmployeeList(orgId);
		});
		$(".oraganization_table").on('click', '.details_link', function() {
			var employeeId = $(this).attr("employeeId");
			showEditEmployeeDialog(employeeId);
			setEditEmployeeDialogDisabled();
			dialog.showDialog($("#editEmployeeDialog"), function() {
				employeeEven();
				if ($(".dialogHandlerBtn").hasClass('editclass')) {
					removeEditEmployeeDialogDisabled();
					return;
				};
				updateEmployee(employeeId);
			});
		});

		//负责人填写
		$("#addManagerUserId").change(function() {
			if ($("#addManagerUserId").val().length == 0) {
				$("#addManagerUserId").val("");
				$('#addManagerUserIdHidden').val("");
				return;
			};
			setvalueWithBulr();
		});
		//新增部门负责人自动补全
		$("#addManagerUserId").autocomplete(seajs.data.handler + "inquireEmployeeList.json", {
			minChars: 1,
			max: 10,
			width: 152,
			matchCase: false, //不区分大小写
			// matchContains :true,
			// autoFill: false,
			scroll: false,
			dataType: 'json',
			scrollHeight: 500,
			// selectFirst: true,
			//此处为传递参数
			extraParams: {
				orgId: orgId,
				subOrg: 1,
				pageSize: 50,
				sessionUuid: base.getData("sid"),
				appKey: base.getData("appKey")
			},
			//需要把data转换成json数据格式                      
			parse: function(data) {
				return $.map(eval(data.datas), function(row) {
					return {
						data: row,
						value: row.name, //此处无需把全部列列出来，只是两个关键列
						result: row.employeeId
					}
				});
			},
			formatItem: function(data, i, total) {
				return "<table><tr><td align='left'>" + data.name + "</td></tr></table>";
			},
			formatMatch: function(data, i, total) {
				return data.name;
			},
			formatResult: function(data, value) {
				return data.name;
			}
		}).result(function(event, data, formatted) { //回调
			$("#addManagerUserId").val(data.name);
			$('#addManagerUserIdHidden').val(data.employeeId);
		});
		
		$("#editOrgManagerUser").change(function() {
			$("#editOrgManagerUserId").val($("#editOrgManagerUser").find("option:selected").text());
			$('#editmanagerUserIdHidden').val($(this).val());
			
		});
		
		//编辑部门负责人自动补全
//		$("#editOrgManagerUserId").autocomplete(seajs.data.handler + "inquireEmployeeList.json", {
//			minChars: 1,
//			max: 10,
//			width: 152,
//			matchCase: false, //不区分大小写
//			// matchContains :true,
//			// autoFill: false,
//			scroll: false,
//			dataType: 'json',
//			scrollHeight: 500,
//			//此处为传递参数
//			extraParams: {
//				orgId: orgId,
//				subOrg: 1,
//				pageSize: 50,
//				sessionUuid: base.getData("sid"),
//				appKey: base.getData("appKey")
//			},
//			//需要把data转换成json数据格式                      
//			parse: function(data) {
//				return $.map(eval(data.datas), function(row) {
//					return {
//						data: row,
//						value: row.name, //此处无需把全部列列出来，只是两个关键列
//						result: row.employeeId
//					}
//				});
//			},
//			formatItem: function(data, i, total) {
//				return "<table><tr><td align='left'>" + data.name + "</td></tr></table>";
//			},
//			formatMatch: function(data, i, total) {
//				return data.name;
//			},
//			formatResult: function(data, value) {
//				return data.name;
//			}
//		}).result(function(event, data, formatted) { //回调
//			$("#editOrgManagerUserId").val(data.name);
//			$('#editmanagerUserIdHidden').val(data.employeeId);
//		});

		//编辑部门上级部门自动补全
		$("#editOrgParentId").autocomplete(seajs.data.handler + "inquireOrganizationByKeyword.json", {
			minChars: 1,
			max: 10,
			width: 152,
			matchCase: false, //不区分大小写
			// matchContains :true,
			// autoFill: false,
			scroll: false,
			dataType: 'json',
			scrollHeight: 500,
			//此处为传递参数
			extraParams: {
				excludeOrgId: $("#orgId").val(),
				pageSize: 50,
				sessionUuid: base.getData("sid"),
				appKey: base.getData("appKey")
			},
			//需要把data转换成json数据格式                      
			parse: function(data) {
				return $.map(eval(data.datas), function(row) {
					return {
						data: row,
						value: row.name, //此处无需把全部列列出来，只是两个关键列
						result: row.orgId
					}
				});
			},
			formatItem: function(data, i, total) {
				return "<table><tr><td align='left'>" + data.name + "</td></tr></table>";
			},
			formatMatch: function(data, i, total) {
				return data.name;
			},
			formatResult: function(data, value) {
				return data.name;
			}
		}).result(function(event, data, formatted) { //回调
			$("#editOrgParentId").val(data.name);
			$("#editparentOrgIdHidden").val(data.orgId);
		});
		//详情职位部门自动补全
		$("#orgName1").autocomplete(seajs.data.handler + "inquireOrganizationByKeyword.json", {
			minChars: 1,
			max: 10,
			width: 152,
			matchCase: false, //不区分大小写
			// matchContains :true,
			// autoFill: false,
			scroll: false,
			dataType: 'json',
			scrollHeight: 500,
			//此处为传递参数
			extraParams: {
				excludeOrgId: $("#orgId").val(),
				pageSize: 50,
				sessionUuid: base.getData("sid"),
				appKey: base.getData("appKey")
			},
			//需要把data转换成json数据格式                      
			parse: function(data) {
				return $.map(eval(data.datas), function(row) {
					return {
						data: row,
						value: row.name, //此处无需把全部列列出来，只是两个关键列
						result: row.orgId
					}
				});
			},
			formatItem: function(data, i, total) {
				return "<table><tr><td align='left'>" + data.name + "</td></tr></table>";
			},
			formatMatch: function(data, i, total) {
				return data.name;
			},
			formatResult: function(data, value) {
				return data.name;
			}
		}).result(function(event, data, formatted) { //回调
			$("#orgName1").val(data.name);
			$("#editcurrentOrgIdHidden1").val(data.orgId);
		});
	};
	//新增人员绑定事件
	var employeeEven = function() {
			//新增人员上传头像
			$("#addEmployeeDialog").on("change", "#uploadImg", function() {
				uploadHeadPicture();
			});


			//编辑人员上传头像
			$("#editUploadImg").on('change', function() {
				editHeadPicture();
			});
		}
		//查询权限角色列表
	var inquireRoleList = function() {
		base.fnAjax({
			action: "inquireRoleList.json",
			async:false,
			oData: {
				pageSize: 1000
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var tpl = $("#roleListTpl").html();
					var html = juicer(tpl, data);
					$("#roleListBody").html(html);

					$("#roleListBody").multiSelect({
						noneSelected: "请选择"
					}, null);

					$(".multiSelectOptions input").unbind("click").click(function() {
						var str = [];
						$("#roleIds").html("");
						$.each($(".multiSelectOptions input:checked"), function() {
							$("#roleIds").append("<input type='hidden' name='roleId' value='" + $(this).val() + "' />");
						});
					});

				} else {
					util.error("信息获取失败");
				}
			}
		});
	};
	//分配权限
	var createRoleEmployee = function() {
			base.fnAjax({
				action: "createRoleEmployee.json",
				nocode: true,
				oData: {}, //传递参数
				fnSuccess: function(data) {
					if (data.status == 200) {} else {
						util.error("信息获取失败");
					}
				}
			});
		}
		//去除编辑状态的
	var setEditEmployeeDialogDisabled = function() {
		$(".edit").addClass('editclass');
		$(".edit").text("编辑");
		$("#editUploadImg").attr("disabled", "disabled");
		$("#editEmployeeName").attr("disabled", "disabled");
		$("#editEmployeeEmpCode").attr("disabled", "disabled");
		$("#editEmployeeMobile").attr("disabled", "disabled");
		$("#editEmployeePosition").attr("disabled", "disabled");
		$("#editEmployeeEmail").attr("disabled", "disabled");
		$("#editEmployeeIntroduction").attr("disabled", "disabled");
	};
	//增加编辑状态
	var removeEditEmployeeDialogDisabled = function() {
		$(".edit").removeClass('editclass');
		$(".edit").text("确定");
		$("#editUploadImg").removeAttr("disabled");
		$("#editEmployeeName").removeAttr("disabled");
		$("#editEmployeeEmpCode").removeAttr("disabled");
		$("#editEmployeeMobile").removeAttr("disabled");
		$("#editEmployeePosition").removeAttr("disabled");
		$("#editEmployeeEmail").removeAttr("disabled");
		$("#editEmployeeIntroduction").removeAttr("disabled");
	};
	//负责人填写
	var setvalueWithBulr = function() {
		var keyword = $("#addManagerUserId").val();
		keyword = keyword.replace(/[ ]/g, "")
		if (keyword == "") {
			return;
		};
		base.fnAjax({
			action: "inquireEmployeeList.json",
			nocode: true,
			oData: {
				subOrg: 1,
				orgId: 0,
				keyword: keyword,
				pageSize: 50
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					if (data.datas.length > 0) {
						$("#addManagerUserId").val(data.datas[0].name);
						$('#addManagerUserIdHidden').val(data.datas[0].employeeId);
					} else {
						$('#addManagerUserIdHidden').val("");
					};
				} else {
					util.error("信息获取失败");
				}
			},
			error: function() {
				$('#addManagerUserIdHidden').val("");
			}
		});

	};
	//编辑部门绑定部门信息
	var showEditDepartmentDialog = function() {
		base.fnAjax({
			action: "inquireOrganizationDetail.json",
			oData: {
				orgId: orgId,

			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var organizationDetail = data.datas[0];
					$("#editOrgCode").val(organizationDetail.orgCode);
					$("#editOrgName").val(organizationDetail.name);
					$("#editOrgOnDutyHour").val(organizationDetail.onDutyHour);
					$("#editOrgLevel").val(organizationDetail.level);
					$("#editOrgTelephone").val(organizationDetail.telephone);
					$("#editOrgFax").val(organizationDetail.fax);
					$("#editOrgParentId").val(organizationDetail.parentOrgName);
					$("#editOrgId").val(organizationDetail.orgId);
					$("#editparentOrgIdHidden").val(organizationDetail.parentOrgId);
					$("#editmanagerUserIdHidden").val(organizationDetail.managerUserId);
					$("#editOrgManagerUserId").val(organizationDetail.managerUserName);
					
					loadEmpInfo(organizationDetail.orgId);
				} else {
					util.error("信息获取失败");
				}
			}
		});
	};
	
	//加载部门员工信息
	var loadEmpInfo=function(orgId){
		var editmanagerUserIdHidden=$("#editmanagerUserIdHidden").val();
		$("#editOrgManagerUser").html("");
		base.fnAjax({
			action: "inquireEmployeeList.json",
			nocode: true,
			oData: {
				subOrg: 0,
				orgId: orgId,
				pageSize: 50
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					if (data.datas.length > 0) {
						for(var i in data.datas){
							if (data.datas.length == 1) {
								$("#editOrgManagerUserId").val(data.datas[i].name);
								$('#editmanagerUserIdHidden').val(data.datas[i].employeeId);
							}
							if(data.datas[i].employeeId==editmanagerUserIdHidden){
								$("#editOrgManagerUser").append("<option selected value="+data.datas[i].employeeId+">"+data.datas[i].name+"</option>");
							}else{
								$("#editOrgManagerUser").append("<option value="+data.datas[i].employeeId+">"+data.datas[i].name+"</option>");
							}
						}
					} else {
						$('#editmanagerUserIdHidden').val("");
					};
				} else {
					util.error("信息获取失败");
				}
			},
			error: function() {
				$('#editmanagerUserIdHidden').val("");
			}
		});
	}
	
	//提交部门更新信息
	var updateOrganization = function() {
		var promptDialog = validate.validateInput($("#editDepartmentDialog"));
		if (promptDialog.length != 0) {
			util.alert(promptDialog);
		} else {
			var body = base.parseForm($("#editDepartmentDialog"));
			body.orgId = $("#editOrgId").val();
			base.fnAjax({
				action: "updateOrganization.json",
				oData: body, //传递参数
				fnSuccess: function(data) {
					if (data.status == 200) {
						initEvent();
						dialog.hideDialog($("#editDepartmentDialog"));
						window.location.reload();

					} else {
						util.error(data.message);
					}
				}
			});
			// promptDialog = validate.isPhone($("#editOrgTelephone"), "请输入正确的手机号！");
			// if (promptDialog.length != 0) {
			//     util.alert(promptDialog);
			// } else {
			// }
		}
	};
	//编辑人员绑定人员信息
	var showEditEmployeeDialog = function(employeeId) {
		base.fnAjax({
			action: "inquireEmployeeDetail.json",
			oData: {
				employeeId: employeeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var employeeDetail = data.datas[0];
					if (employeeDetail.photoId.length != 0) {
						editImgSrc = imgSrc = employeeDetail.photoId;
						//						$("#editUploadImgDiv").css("backgroundImage", "url('/finance/api/v1.0/downloadFile.file?fileUuid=" + editImgSrc + "')");
						$("#editUploadImgDiv").append('<img class="headImage" src="/finance/api/v1.0/downloadFile.file?fileUuid=' + imgSrc + '">');
					} else {
						$("#editUploadImgDiv").css("backgroundImage", "url('../../../res/images/icon/addfile.png')");
						$("#editUploadImgDiv").find("img").remove();
					}
					$("#editEmployeeName").val(employeeDetail.name);

					if (employeeDetail.gender == 1) {
						$("#editEmployeeDialog #gender1_edit").prop("checked", "checked");
					};
					if (employeeDetail.gender == 2) {
						$("#editEmployeeDialog #gender2_edit").prop("checked", "checked");
					};

					$("#editEmployeeAccount").val(employeeDetail.accounts);
					$("#editEmployeeEmpCode").val(employeeDetail.empCode);
					$("#editEmployeeMobile").val(employeeDetail.mobile);
					$("#editEmployeeEmail").val(employeeDetail.email);
					$("#currentArea").val(employeeDetail.currentArea);
					$("#editEmployeeIntroduction").val(employeeDetail.description);
					for (var i = 0; i < employeeDetail.positions.length; i++) {
						var position = employeeDetail.positions[i];
						$("#editEmployeeOrgName").val(position.orgName);
						$("#editEmployeePosition").val(position.position);
						//						}
					}
				} else {
					util.error("信息获取失败");
				}
			}
		});
	};
	//提交人员信息
	var updateEmployee = function(employeeId) {
		var promptDialog = validate.validateInput($("#editEmployeeDialog"));
		if (promptDialog.length != 0) {
			util.alert(promptDialog);
		} else {
			promptDialog = validate.isPhone($("#editEmployeeMobile"), "请输入正确的手机号！");
			if (promptDialog.length != 0) {
				util.alert(promptDialog);
				return;
			}
			promptDialog = validate.isEmail($("#editEmployeeEmail"), "请输入正确的邮箱！");
			if (promptDialog.length != 0) {
				util.alert(promptDialog);
				return;
			}
			var body = base.parseForm($("#editEmployeeDialog"));
			if (editImgSrc != imgSrc) {
				body.photoId = imgSrc;
			}
			body.photoId = imgSrc;
			body.employeeId = employeeId;
			base.fnAjax({
				action: "updateEmployee.json",
				oData: body, //传递参数
				fnSuccess: function(data) {
					if (data.status == 200) {
						oData.pageIndex = 1;
						base.fnAjax({
							action: "updateEmployeePosition.json",
							oData: {
								orgId: orgId,
								empId: employeeId,
								position: $("#editEmployeePosition").val()
							}, //传递参数
							fnSuccess: function(data) {
								if (data.status == 200) {
									oData.pageIndex = 1;
									inquireEmployeeList(orgId);
									dialog.hideDialog($("#editEmployeeDialog"));
								} else {
									util.error(data.message);
								}
							}
						});
					} else {
						util.error(data.message);
					}
				}
			});
		}
	};

	//新增人员上传头像
	var uploadHeadPicture = function() {
		if ($("#uploadImg").val() != "") {
			$.ajaxFileUpload({
				url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
				secureuri: false,
				fileElementId: "uploadImg",
				dataType: 'json',
				success: function(data) {
					imgSrcTest = data.data[0].fileUuid;
					//					$("#uploadImgDiv").css("backgroundImage", "url('/finance/api/v1.0/downloadFile.file?fileUuid=" + imgSrcTest + "')");
					$("#uploadImgDiv").append('<img class="headImage" src="/finance/api/v1.0/downloadFile.file?fileUuid=' + imgSrcTest + '">');
				},
				complete: function(xml) {
					$("#uploadImg").unbind().on('change', function() {
						uploadHeadPicture($("#uploadImg"), $("#uploadImgDiv"));
					});
				},
				error: function(data, status, e) {
					if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
				}
			});
		} else {
			util.alert("请选择文件！");
		}
	};
	//修改人员上传头像
	var editHeadPicture = function() {
		if ($("#editUploadImg").val() != "") {
			$.ajaxFileUpload({
				url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
				secureuri: false,
				fileElementId: $("#editUploadImg").attr("id"),
				dataType: 'json',
				success: function(data) {
					imgSrc = data.data[0].fileUuid;
					//					$("#editUploadImgDiv").css("backgroundImage", "url('/finance/api/v1.0/downloadFile.file?fileUuid=" + imgSrc + "')");
					$("#editUploadImgDiv").append('<img class="headImage" src="/finance/api/v1.0/downloadFile.file?fileUuid=' + imgSrc + '">');
				},
				complete: function(xml) {
					$("#editUploadImg").unbind().on('change', function() {
						editHeadPicture();
					});
				},
				error: function(data, status, e) {
					if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
				}
			});
		} else {
			util.alert("请选择文件！");
		}
	};
	var str = "";
	//查询权限树
	// var inquireOrganizationTree = function() {
	// 	base.fnAjax({
	// 		action: "inquireOrganizationTree.json",
	// 		async: false,
	// 		oData: {}, //传递参数
	// 		fnSuccess: function(data) {
	// 			if (data.status == 200) {
	// 				var rootNode = data.datas[0];
	// 				orgId = rootNode.organizationId;
	// 				str += " <li organizationId='" + rootNode.organizationId + "' >" + rootNode.name
	// 				str += "<ul class='noChildrenUl topMenu' >";
	// 				oData.pageIndex = 1;
	// 				inquireEmployeeList(orgId);
	// 				$("#departmentName").html(rootNode.name);
	// 				companyName = rootNode.name;
	// 				showChildOrganizationTree(rootNode.subOrgs);
	// 				$(".treeMenu > ul").html(str);
	// 				str = "";
	// 			} else {
	// 				util.error("信息获取失败");
	// 			}
	// 		}
	// 	});
	// };
	//展示子部门
	// var showChildOrganizationTree = function(subOrgs) {
	// 	for (var i = 0; i < subOrgs.length; i++) {
	// 		subOrg = subOrgs[i];
	// 		if (subOrg.subOrgs.length > 0) {
	// 			str += " <li class='hasChildrenUlFold' organizationId='" + subOrg.organizationId + "' ><span>" + subOrg.name + "</span>";
	// 			str += " <ul class='noChildrenUl'>";
	// 			showChildOrganizationTree(subOrg.subOrgs, str);
	// 		} else {
	// 			str += "<li organizationId='" + subOrg.organizationId + "'><span>" + subOrg.name + "</span></li>";
	// 		}
	// 	}
	// 	str += "</ul></li>";
	// };
	//获取部门详细信息
	var inquireOrganizationDetail = function(orgId) {
	
			base.fnAjax({
				action: "inquireOrganizationDetail.json",
				oData: {
					orgId: orgId
				}, //传递参数
				fnSuccess: function(data) {
					if (data.status == 200) {
						$(".begin").removeClass("none");
						var organizationDetail = data.datas[0];
						$("#departmentName").html(organizationDetail.name);
						$("#name").html(organizationDetail.name);
						$("#orgCode").html(organizationDetail.orgCode);
						$("#telephone").html(organizationDetail.telephone);
						$("#fax").html(organizationDetail.fax);
						$("#onDutyHour").html(organizationDetail.onDutyHour);
						$("#managerUserName").html(organizationDetail.managerUserName);
					} else {
						util.error(3, "信息获取失败");
					}
				}
			});
//		if (orgId > 0) {
//		} else {
//			$(".begin").addClass("none");
//			$("#departmentName").html(companyName);
//		}
	};
	//新增部门信息
	var createOrganization = function() {
		var promptDialog = validate.validateInput($("#addDepartmentDialog"));
		if (promptDialog.length != 0) {
			util.alert(promptDialog);
		} else {
			var body = base.parseForm($("#addDepartmentDialog"));
			body.parentOrgId = orgId;
			base.fnAjax({
				action: "createOrganization.json",
				oData: body, //传递参数
				fnSuccess: function(data) {
					if (data.status == 200) {
						dialog.hideDialog($("#addDepartmentDialog"));
						init();
					} else {
						util.error(data.message);
					}
				}
			});
			// promptDialog = validate.isPhone($("#addTelephone"), "请输入正确的手机号！");
			// if (promptDialog.length != 0) {
			//     util.alert(promptDialog);
			// } else {
			// }
		}

	};
	//新增员工
	var createEmployee = function() {

		var promptDialog = validate.validateInput($("#addEmployeeDialog"));
		if (promptDialog.length != 0) {
			util.alert(promptDialog);
		} else {
			promptDialog = validate.isPhone($("#employeeMobile"), "请输入正确的手机号！");
			if (promptDialog.length != 0) {
				util.alert(promptDialog);
				return;
			}
			promptDialog = validate.isEmail($("#employeeEmail"), "请输入正确的邮箱！");
			if (promptDialog.length != 0) {
				util.alert(promptDialog);
				return;
			}
			var body = base.parseForm($("#addEmployeeDialog"));
			body.orgId = orgId;
			body.photoId = imgSrcTest;
			imgSrcTest = "";
			base.fnAjax({
				action: "createEmployee.json",
				oData: body, //传递参数
				fnSuccess: function(data) {
					if (data.status == 200) {
						base.alert(1, "添加成功！");
						oData.pageIndex = 1;
						inquireEmployeeList(orgId);
						$("#uploadImgDiv").css("backgroundImage", "url('../../../res/images/icon/addfile.png')");
						$("#description").val("");
						dialog.hideDialog($("#addEmployeeDialog"));
						$(".headImage").remove();
						
						synchronousToCrm("", body.name, body.mobile, body.empCode + "@zjjr56");
					} else {
						$("#uploadImgDiv").css("backgroundImage", "url('../../../res/images/icon/addfile.png')");
						util.error(data.message);
					}
				}
			});
		}
	};
	
	var synchronousToCrm = function(address, name, mobile, accountName) {
		base.fnAjax({
			action: "synchronousToCrm.json",
			oData: {
				address: address,
				name: name,
				mobile: mobile,
				accountName: accountName,
				is_inside: 0
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					
				} else {
				}
			}
		});
	};
	//显示子节点
	//	var showChilrenNode = function(obj) {
	//		if (obj.find("ul").length > 0) { //当前节点存在子节点的
	//			var clssName = obj.attr("class").toString();
	//			if (clssName.indexOf("hasChildrenUlFold") != -1) { //表示未展开状态
	//				obj.children("ul").show();
	//				obj.removeClass("hasChildrenUlFold").addClass("hasChildrenUlUnfold");
	//			} else {
	//				traverseChildrenNode(obj);
	//				obj.children("ul").hide();
	//				obj.removeClass("hasChildrenUlUnfold").addClass("hasChildrenUlFold");
	//			}
	//		}
	//		return false;
	//	};
	//遍历子节点
	//	var traverseChildrenNode = function(obj) { //遍历子节点
	//		var childrenNodes = obj.children("ul").children("li");
	//		for (var i = 0; i < childrenNodes.length; i++) {
	//			var childrenNode = $(childrenNodes[i]);
	//			if (childrenNode.find("ul").length > 0) {
	//				traverseChildrenNode(childrenNode);
	//				var childrenClassName = childrenNode.attr("class").toString();
	//				if (childrenClassName.indexOf("hasChildrenUlFold") == -1) {
	//					childrenNode.children("ul").hide();
	//					childrenNode.removeClass("hasChildrenUlUnfold").addClass("hasChildrenUlFold");
	//				}
	//			}
	//		}
	//		return false;
	//	};
	//查询员工信息列表
	var inquireEmployeeList = function(orgId) {
		if ($("#subOrgs").is(':checked')) {
			subOrg = 1;
		} else {
			subOrg = 0;
		}
		var keyword = null;
		if ($("#keyword").val().length > 0) {
			keyword = $("#keyword").val();
		};
		oData.subOrg = subOrg;
		oData.orgId = orgId;
		oData.keyword = keyword;
		// 初始化表体内容
		var toTable = function(data) {
			var tpl = [
				'{@each datas as it}',
				'<tr class="" >',
				'<td class="pl10">${it.empCode}</td>',
				'<td class="pl10">${it.name}</td>',
				'{@if it.gender == 1}',
				'<td class="pl10">男</td>',
				'{@else}',
				'<td class="pl10">女</td>',
				'{@/if}',
				'<td class="pl10">${it.mobile}</td>',
				'<td class="pl10">${it.currentArea}</td>',
				'<td class="pl10">${it.accounts}</td>',
				'<td class="pl10"><span class="details_link" employeeId="${it.employeeId}">详情&nbsp;</span><span class="bar">|</span><span class="delete_btn" employeeId="${it.employeeId}" employeeName="${it.name}">&nbsp;删除<span class="bar">|</span></span><span class="permision_btn" employeeId="${it.employeeId}" employeeName="${it.name}">&nbsp;权限<span class="bar">|</span></span> <span class="move_btn" employeeId="${it.employeeId}" employeeName="${it.name}">&nbsp;移动</span></td>',
				'</tr>',
				'{@/each}'
			].join('');
			$(".oraganization_table tbody").html("");
			$(".oraganization_table tbody").html(juicer(tpl, data));
		}
		base.fnAjax({
			action: "inquireEmployeeList.json",
			oData: oData,
			fnSuccess: function(data) {
				if (data.status == 200) {
					toTable(data);
					totalPageCount = data.totalPageCount;
					totalRecordCount = data.totalRecordCount;
					base.pageControl($("#pagenation"), totalRecordCount, data.pageIndex, data.pageSize, function(p) {
						oData.pageIndex = p;
						inquireEmployeeList(oData.orgId);
					});
				} else {
					util.error("信息获取失败");
				}
			}
		});
	};
	/*删除员工*/
	var deleteEmployee = function(employeeId) {
		var employeeIds = new Array();
		employeeIds[0] = employeeId;
		base.fnAjax({
			action: "deleteEmployee.json",
			oData: {
				empIds: employeeIds
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					oData.pageIndex = 1;
					inquireEmployeeList(orgId);
					dialog.hideDialog($("#confirmDialog"));
				} else {
					util.error(data.message);
				}
			}
		});
	};
	/*删除部门信息*/
	var deleteOrganization = function() {
		base.fnAjax({
			action: "deleteOrganization.json",
			oData: {
				orgId: orgId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					dialog.hideDialog($("#confirmDialog"));
					window.location.reload();
				} else {
					util.error(data.message);
				}
			}
		});
	};

	var inquireEmployeeRoleList = function(employeeId) {
		var obj = [];
		base.fnAjax({
			action: "inquireEmployeeRoleList.json",
			async: false,
			oData: {
				employeeId: employeeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					$.each(data.datas, function() {
						var o = {};
						o.createTime = this.createTime;
						o.roleName = this.roleName;
						o.roleId = this.roleId;
						obj.push(o);
					});
				} else {
					util.error(data.message);
				}
			}
		});
		return obj;
	};
	
	/*查询部门列表*/
	var inquireOrganizationList = function() {
		var obj = [];
		base.fnAjax({
			action: "inquireOrganizationList.json",
			async: false,
			oData: {
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var tpl = $("#positionListTpl").html();
					var html = juicer(tpl, data);
					html = "<option value=''>请选择</option>" + html;
					$("#positionListBody").html(html);
				} else {
					util.error(data.message);
				}
			}
		});
		return obj;
	};
	
	/*查询员工的详细信息*/
	var inquireEmployeeDetail = function(employeeId) {
		base.fnAjax({
			action: "inquireEmployeeDetail.json",
			oData: {
				employeeId: employeeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var employeeDetail = data.datas[0];
				} else {
					util.alert("服务器异常，请稍后再试！");
				}
			}
		});
	};
	return {
		init: init
	};
});